"""
角色数据访问对象 (Role DAO)
提供自定义角色的数据库操作接口
"""

from typing import List, Optional, Dict, Any
from datetime import datetime
import uuid
import logging

from .supabase_client import get_supabase_client
from pydantic import BaseModel

logger = logging.getLogger(__name__)

# 角色特征模型
class RoleTrait(BaseModel):
    key: str
    value: str

# 自定义角色模型
class CustomRoleModel(BaseModel):
    id: str
    user_id: str = '00000000-0000-0000-0000-000000000000'  # 默认用户ID（单用户模式）
    name: str
    title: Optional[str] = ""
    input_spec: str
    output_spec: str
    custom_traits: List[RoleTrait] = []
    system_prompt_snapshot: str
    usage_count: int = 0
    last_used_at: Optional[datetime] = None
    created_at: datetime
    updated_at: datetime

class RoleDAO:
    """角色数据访问对象"""
    
    def __init__(self):
        self.supabase = get_supabase_client()
    
    async def create_custom_role(self, name: str, title: str, input_spec: str, 
                               output_spec: str, custom_traits: List[RoleTrait],
                               system_prompt_snapshot: str, 
                               user_id: str = '00000000-0000-0000-0000-000000000000',
                               id: Optional[str] = None, **kwargs) -> CustomRoleModel:
        """创建自定义角色"""
        try:
            # 将RoleTrait对象转换为字典
            traits_data = [trait.dict() for trait in custom_traits]
            
            role_data = {
                'name': name,
                'user_id': user_id,
                'title': title,
                'input_spec': input_spec,
                'output_spec': output_spec,
                'custom_traits': traits_data,
                'system_prompt_snapshot': system_prompt_snapshot,
                'usage_count': kwargs.get('usage_count', 0)
            }
            
            if id:
                role_data['id'] = id
            
            result = self.supabase.table('custom_roles').insert(role_data).execute()
            
            if result.data:
                role_dict = result.data[0]
                # 转换custom_traits回RoleTrait对象
                role_dict['custom_traits'] = [RoleTrait(**trait) for trait in role_dict.get('custom_traits', [])]
                return CustomRoleModel(**role_dict)
            else:
                raise Exception("创建自定义角色失败，未返回数据")
                
        except Exception as e:
            logger.error(f"创建自定义角色失败: {e}")
            raise
    
    async def get_custom_role(self, role_id: str) -> Optional[CustomRoleModel]:
        """根据ID获取自定义角色"""
        try:
            result = self.supabase.table('custom_roles').select('*').eq('id', role_id).execute()
            
            if result.data:
                role_dict = result.data[0]
                # 转换custom_traits
                role_dict['custom_traits'] = [RoleTrait(**trait) for trait in role_dict.get('custom_traits', [])]
                return CustomRoleModel(**role_dict)
            return None
            
        except Exception as e:
            logger.error(f"获取自定义角色失败 {role_id}: {e}")
            return None
    
    async def get_all_custom_roles(self) -> List[CustomRoleModel]:
        """获取所有自定义角色"""
        try:
            result = self.supabase.table('custom_roles').select('*').order('created_at', desc=True).execute()
            
            roles = []
            if result.data:
                for role_dict in result.data:
                    # 转换custom_traits
                    role_dict['custom_traits'] = [RoleTrait(**trait) for trait in role_dict.get('custom_traits', [])]
                    roles.append(CustomRoleModel(**role_dict))
            
            return roles
            
        except Exception as e:
            logger.error(f"获取自定义角色列表失败: {e}")
            return []
    
    async def update_custom_role(self, role_id: str, updates: Dict[str, Any]) -> Optional[CustomRoleModel]:
        """更新自定义角色"""
        try:
            # 如果更新包含custom_traits，需要转换格式
            if 'custom_traits' in updates and isinstance(updates['custom_traits'], list):
                if updates['custom_traits'] and isinstance(updates['custom_traits'][0], RoleTrait):
                    updates['custom_traits'] = [trait.dict() for trait in updates['custom_traits']]
            
            result = self.supabase.table('custom_roles').update(updates).eq('id', role_id).execute()
            
            if result.data:
                role_dict = result.data[0]
                # 转换custom_traits
                role_dict['custom_traits'] = [RoleTrait(**trait) for trait in role_dict.get('custom_traits', [])]
                return CustomRoleModel(**role_dict)
            return None
            
        except Exception as e:
            logger.error(f"更新自定义角色失败 {role_id}: {e}")
            return None
    
    async def delete_custom_role(self, role_id: str) -> bool:
        """删除自定义角色"""
        try:
            result = self.supabase.table('custom_roles').delete().eq('id', role_id).execute()
            return len(result.data) > 0 if result.data else False
            
        except Exception as e:
            logger.error(f"删除自定义角色失败 {role_id}: {e}")
            return False
    
    async def increment_usage(self, role_id: str) -> bool:
        """增加角色使用次数"""
        try:
            # 先获取当前使用次数
            current_result = self.supabase.table('custom_roles').select('usage_count').eq('id', role_id).execute()
            
            if not current_result.data:
                return False
            
            current_usage = current_result.data[0]['usage_count']
            
            # 更新使用次数和最后使用时间
            updates = {
                'usage_count': current_usage + 1,
                'last_used_at': datetime.now().isoformat()
            }
            
            result = self.supabase.table('custom_roles').update(updates).eq('id', role_id).execute()
            return len(result.data) > 0 if result.data else False
            
        except Exception as e:
            logger.error(f"增加角色使用次数失败 {role_id}: {e}")
            return False
    
    async def check_role_name_exists(self, name: str, exclude_id: Optional[str] = None) -> bool:
        """检查角色名称是否已存在"""
        try:
            query_builder = self.supabase.table('custom_roles').select('id').eq('name', name)
            
            if exclude_id:
                query_builder = query_builder.neq('id', exclude_id)
            
            result = query_builder.execute()
            return len(result.data) > 0 if result.data else False
            
        except Exception as e:
            logger.error(f"检查角色名称是否存在失败: {e}")
            return False
    
    def get_builtin_roles(self) -> List[Dict[str, Any]]:
        """获取预设角色列表（硬编码，不存储在数据库）"""
        return [
            {
                "id": "emma",
                "name": "心理咨询师 Emma",
                "title": "心理咨询师",
                "description": "温暖专业的心理咨询师，善于倾听和情绪疏导",
                "icon": "🌸",
                "color": "pink",
                "specialty": "情绪管理、人际关系、个人成长",
                "is_builtin": True
            },
            {
                "id": "sophie", 
                "name": "学习导师 Sophie",
                "title": "学习导师",
                "description": "经验丰富的学习导师，擅长知识讲解和学习指导",
                "icon": "📚",
                "color": "blue", 
                "specialty": "学习方法、知识讲解、考试辅导",
                "is_builtin": True
            },
            {
                "id": "mike",
                "name": "编程专家 Mike", 
                "title": "高级工程师",
                "description": "资深编程专家，精通多种编程语言和技术",
                "icon": "💻",
                "color": "green",
                "specialty": "代码开发、技术架构、问题调试", 
                "is_builtin": True
            }
        ]